package io.github.wanggit.antrpc.client.config.workers;

import io.github.wanggit.antrpc.IAntrpcContext;
import io.github.wanggit.antrpc.commons.config.workers.IChangeWorker;
import io.vavr.Tuple2;
import io.vavr.collection.List;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public abstract class ChangeWorkerHelper {

    private static final Map<Class<? extends IChangeWorker>, IChangeWorker> cache = new HashMap<>();

    public static IChangeWorker createWorker(Class<? extends IChangeWorker> clazz) {
        if (cache.containsKey(clazz)) {
            return cache.get(clazz);
        }
        IChangeWorker changeWorker = null;
        try {
            changeWorker = clazz.getConstructor().newInstance();
            cache.put(clazz, changeWorker);
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("Instance " + clazz.getName() + " ERROR. ", e);
            }
        }
        return changeWorker;
    }

    public static IChangeWorker createWorker(
            Tuple2<List<String>, Class<? extends IChangeWorker>> tuple2,
            IAntrpcContext antrpcContext) {
        if (cache.containsKey(tuple2._2)) {
            return cache.get(tuple2._2);
        }
        IChangeWorker changeWorker = null;
        try {
            changeWorker =
                    tuple2._2
                            .getConstructor(IAntrpcContext.class, List.class)
                            .newInstance(antrpcContext, tuple2._1);
            cache.put(tuple2._2, changeWorker);
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("Instance " + tuple2._2.getName() + " ERROR. ", e);
            }
        }
        return changeWorker;
    }
}
